package com.gl.saasservice.adspace.service;

import com.gl.common.vo.ApiData;
import com.gl.framework.web.response.Result;
import com.gl.saasservice.adspace.entity.SaasAdSpace;
import com.gl.saasservice.adspace.repository.SaasAdSpaceRepository;
import com.gl.saasservice.adspace.vo.SaasAdSpaceVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

/**
 * 广告位置管理服务
 */
@Service
public class SaasAdSpaceService {

    private static final Logger LOG = LoggerFactory.getLogger(SaasAdSpaceService.class);

    public static final String HASH_ALGORITHM = "SHA-1";
    public static final int HASH_INTERATIONS = 1024;
    private static final int SALT_SIZE = 8;

    @Autowired
    private JdbcTemplate jdbcTemplate;
    @Autowired
    private SaasAdSpaceRepository saasAdSpaceRepository;

    /**
     * 广告位管理页列表
     *
     * @param pageNumber
     * @param pageSize
     * @param filter
     * @param sorts
     * @return
     */
    public Result pages(Integer pageNumber, Integer pageSize, SaasAdSpaceVO filter, String sorts) {
        LOG.info("---SaasAdSpaceService.pages---> pageNumber={}, pageSize={}, filter={}, sorts={}", pageNumber, pageSize, filter, sorts);

        ApiData<SaasAdSpaceVO> apiData = new ApiData<>();
        try {
            String columns = "SELECT id,code,name FROM saas_ad_space ";
            String count = "SELECT COUNT(1) FROM saas_ad_space  ";
            StringBuffer where = new StringBuffer(" where  1 =1 ");
            String offsets = " LIMIT ? OFFSET ?";

            List<Object> args = new ArrayList<>();

            if (filter != null) {
                if (StringUtils.isNotBlank(filter.getCode())) {
                    where.append(" AND code LIKE ? ");
                    args.add("%" + filter.getCode() + "%");
                }
                if (StringUtils.isNotBlank(filter.getName())) {
                    where.append(" AND  name LIKE ?\n");
                    args.add("%" + filter.getName() + "%");
                }
            }

            // 查询总记录数
            Long total = jdbcTemplate.queryForObject(count + where, Long.class, args.toArray());
            if (total == 0) {
                return Result.success(apiData);
            }
            // 查询分页数据
            where.append(" ORDER BY ").append(StringUtils.isNotEmpty(sorts) ? sorts : " id ").append("\n").append(offsets);

            args.add(pageSize);
            args.add(pageNumber * pageSize);
            List<SaasAdSpaceVO> data = jdbcTemplate.query(columns + where, new BeanPropertyRowMapper<>(SaasAdSpaceVO.class), args.toArray());

            apiData.setTotal(total);
            apiData.setData(data);
            return Result.success(apiData);
        } catch (Exception e) {
            LOG.error("SaasAdSpaceService pages Exception = {}", e.getMessage());
            return Result.fail();
        }
    }

    /**
     * 保存
     * @param vo
     * @return
     */
    public Result save(SaasAdSpaceVO vo) {
        try {

            SaasAdSpace entity =new SaasAdSpace();

            if (vo.getId() == null) {
                entity.setCode(vo.getCode());
                entity.setName(vo.getName());

            }else{

                Optional<SaasAdSpace> optionalSaasAdSpace = saasAdSpaceRepository.findById(vo.getId());
                if (!optionalSaasAdSpace.isPresent()) {
                    return Result.fail("id不存在无法保存");
                }
                entity = optionalSaasAdSpace.get();
                entity.setId(vo.getId());
                entity.setCode(vo.getCode());
                entity.setName(vo.getName());
            }

            saasAdSpaceRepository.save(entity);

            return Result.success(null);
        } catch (Exception e) {
            LOG.error("SaasAdSpaceService save Exception = {}", e.getMessage());
            return Result.fail();
        }
    }

    /**
     * 删除
     *
     * @param id
     * @return
     */
    public Result delete(Long id) {

        try {
            Optional<SaasAdSpace> saasAdSpace = saasAdSpaceRepository.findById(id);
            if (!saasAdSpace.isPresent()) {
                return Result.fail("id不存在无法删除");
            }
            saasAdSpaceRepository.deleteById(id);

            return Result.success(null);
        } catch (Exception e) {
            LOG.error("SaasAdSpaceService delete Exception = {}", e.getMessage());
            return Result.fail();
        }
    }

    /**
     * 获取详情
     *
     * @return
     */
    public Result find(Long id) {

        try {
            Optional<SaasAdSpace> optional = saasAdSpaceRepository.findById(id);
            if (!optional.isPresent()) {
                return Result.fail("id不存在");
            }
            SaasAdSpace saasAdSpace = optional.get();

            return Result.success(saasAdSpace);
        } catch (Exception e) {
            LOG.error("SaasAdSpaceService find Exception = {}", e.getMessage());
            return Result.fail();
        }
    }


    /**
     * 获取所有广告位
     *
     * @return
     */
    public Result findAll() {

        List<SaasAdSpace> all = saasAdSpaceRepository.findAll();

        return Result.success(all);
    }


}